#!/bin/bash
source tools/getenv.sh

validCurrDirIsLink

keep_backups=10
if [[ "$env" == "dev" ]]; then
  keep_backups=2
elif [[ "$env" == "test" ]]; then
  keep_backups=5
elif [[ "$env" == "prod" ]]; then
  keep_backups=10
fi


# 获取当前备份目录下的备份数量
backup_count=$(ls -1d "${real_app_root_path}.backup-"* 2>/dev/null | wc -l)

# 如果备份数量超过10个，删除最旧的备份
if [[ $backup_count -ge $keep_backups ]]; then
  old_backups=$(ls -1d "${real_app_root_path}.backup-"* 2>/dev/null | sort | head -n $((backup_count - keep_backups + 1)))
  echo "删除旧备份：$old_backups"
  rm -rf $old_backups
fi



echo "开始备份..."

backup_app_path="${real_app_root_path}.backup-$(date +%Y%m%d%H%M%S)"

echo "current_dir $current_dir"
#echo "back_up_dir $back_up_dir"
echo "backup_app_path $backup_app_path"

rsync -a "$real_app_root_path/" "$backup_app_path"
echo "备份已完成，备份目录为：$backup_app_path"

echo -e "$GREEN 备份完成 $RESET"


#
## 按时间只保留最近的10个，都是在同一个目录下
#ls -t "${real_app_root_path}.backup-*" | tail -n +11 | xargs -I {} rm -rf {}
#
## 按时间只保留最近的10个
#echo "开始清理备份目录..."
#
##ls -t "${real_app_root_path}.backup-*" | tail -n +11 | xargs -I {} rm -rf "$back_up_dir"/{}
#echo "清理完成"
#
